﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace weba.Sales
{
    public partial class ManufacturerList : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
              //  UART.BLL.Sales.Manufacturer bll = new UART.BLL.Sales.Manufacturer();
                //设置经办人
                Accounts_Users currentUser = mk.l.Accounts_Users.FirstOrDefault();
                //设置根部门ID
                var bllDept = mk.l.Accounts_Department.ToList();
                this.lblRootDepartmentID.Text = bllDept.Where(j => j.ClassID == (int.Parse(currentUser.DepartmentID))).FirstOrDefault().RootID.ToString();
                this.lblStrWhere.Text = " RootDepartmentID=" + this.lblRootDepartmentID.Text;
               // this.AspNetPager.RecordCount = bll.GetCount(this.lblStrWhere.Text);
                this.BindData();
                //设置分页页数
                this.txtPageSize.Attributes.Add("onkeydown", "javascript:SetFocusPageSize();");
            }
        }
        private void BindData()
        {
          //  UART.BLL.Sales.Manufacturer bll = new UART.BLL.Sales.Manufacturer();
            var ds = mk.l.Sales_Manufacturer.ToList();
            this.myGridView.DataSource = ds;
            this.myGridView.DataBind();
        }

        /// <summary>
        /// 分页绑定数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AspNetPager_PageChanged(object sender, EventArgs e)
        {
            this.BindData();
        }

        /// <summary>
        /// 删除记录 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void myGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            this.lblMsg.Text = string.Empty;
        Sales_Manufacturer bll = mk.l.Sales_Manufacturer.Single(y => y.ManufacturerID == int.Parse(this.myGridView.DataKeys[e.RowIndex].Values["ManufacturerID"].ToString()));
            try
            {
               // bll.Delete(int.Parse(this.myGridView.DataKeys[e.RowIndex].Values["ManufacturerID"].ToString()));
                mk.l.Sales_Manufacturer.DeleteOnSubmit(bll);
            }
            catch
            {
                this.lblMsg.Text = "删除错误！";
            }
           // this.AspNetPager.RecordCount = bll.GetCount(this.lblStrWhere.Text);
            this.BindData();
        }

        /// <summary>
        /// 选中所有记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void chkSelectAll_CheckedChanged(object sender, EventArgs e)
        {
            //循环判断选中项
            CheckBox chkSelect = new CheckBox();
            CheckBox chkSelectAll = (CheckBox)this.myGridView.HeaderRow.FindControl("chkSelectAll");
            foreach (System.Web.UI.WebControls.GridViewRow gvr in this.myGridView.Rows)
            {
                chkSelect = (CheckBox)(gvr.FindControl("chkSelect"));
                if (chkSelectAll.Checked)
                {
                    chkSelect.Checked = true;
                }
                else
                {
                    chkSelect.Checked = false;
                }
            }

        }

        /// <summary>
        /// Handles the Click event of the lbtnDel control.批量删除数据
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void lbtnDel_Click(object sender, EventArgs e)
        {
            //遍历所有的 chkSelect 找出那些项需要删除
            string strDel = "";
            foreach (GridViewRow gr in this.myGridView.Rows)
            {
                CheckBox chk = (CheckBox)gr.FindControl("chkSelect");
                if (chk.Checked)
                {
                    strDel = strDel + this.myGridView.DataKeys[gr.RowIndex].Value + ",";
                }
            }
            if (strDel != "")
            {
             //   UART.BLL.Sales.Manufacturer bll = new UART.BLL.Sales.Manufacturer();
                //去掉最后的逗号
                strDel = strDel.Substring(0, strDel.Length - 1);
                //删除数据
                try
                {
              //      bll.Delete(" ManufacturerID in (" + strDel + ")");
                }
                catch
                {
                    this.lblMsg.Text = "删除错误！";
                }
                //重新绑定数据
            //    this.AspNetPager.RecordCount = bll.GetCount(this.lblStrWhere.Text);
                this.BindData();
            }
        }

        /// <summary>
        /// 绑定数据时显示状态信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //让数字以文本形式表示
                //e.Row.Cells[1].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
                e.Row.Cells[5].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
                e.Row.Cells[6].Attributes.Add("style", "vnd.ms-excel.numberformat:@");

                DataList myDataList = e.Row.FindControl("myDataList") as DataList;
                if (myDataList != null)
                {
                    this.BindManufactureCode(myDataList, int.Parse(this.myGridView.DataKeys[e.Row.RowIndex].Values["ManufacturerID"].ToString()));
                }
            }
        }

        /// <summary>
        /// Binds the manufacture code.
        /// </summary>
        /// <param name="myDataList">My data list.</param>
        /// <param name="ManufactureID">The manufacture ID.</param>
        private void BindManufactureCode(DataList myDataList, int ManufactureID)
        {
          //  UART.BLL.Sales.ManufacturerCode bllCode = new UART.BLL.Sales.ManufacturerCode();
           var ds = mk.l.Sales_ManufacturerCode.Where(y=>y.ManufacturerID.ToString()==ManufactureID.ToString()).ToList();
            myDataList.DataSource = ds;
            myDataList.DataBind();
        }

        /// <summary>
        /// Handles the Click event of the btnSearch control.查询客户信息
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            this.lblMsg.Text = string.Empty;
            this.lblStrWhere.Text = "";
            //设置查询条件
            //所有的条件都加and 最后再去掉就行了 tnnd早想到这个办法多好啊 不用写那么多if了
            StringBuilder strWhere = new StringBuilder();

            if (this.txtManufacturerName.Text.Trim() != "")
            {
                strWhere.AppendFormat(" and ManufacturerName like '%{0}%'", mk.InputText(this.txtManufacturerName.Text, 50));
            }
            if (this.txtManufacturerCode.Text.Trim() != "")
            {
                strWhere.AppendFormat(" and ManufacturerID in (select ManufacturerID from Sales_ManufacturerCode where Code like '%{0}%')", mk.InputText(this.txtManufacturerCode.Text, 50));
            }
            if (this.txtContactPersonName.Text.Trim() != "")
            {
                strWhere.AppendFormat(" and ContactPersonName like '%{0}%'", mk.InputText(this.txtContactPersonName.Text, 20));
            }
            if (this.txtPhone.Text.Trim() != "")
            {
                strWhere.AppendFormat(" and Phone like '%{0}%'", mk.InputText(this.txtPhone.Text, 20));
            }
            if (this.txtCellPhone.Text.Trim() != "")
            {
                strWhere.AppendFormat(" and CellPhone like '%{0}%'", mk.InputText(this.txtCellPhone.Text, 20));
            }
            if (this.txtAddress.Text.Trim() != "")
            {
                strWhere.AppendFormat(" and Address like '%{0}%'", mk.InputText(this.txtAddress.Text, 100));
            }
            if (strWhere.Length > 0)
            {
                this.lblStrWhere.Text = strWhere.ToString().Substring(5, strWhere.Length - 5);
            }

           // UART.BLL.Sales.Manufacturer bll = new UART.BLL.Sales.Manufacturer();
          //  this.AspNetPager.RecordCount = bll.GetCount(this.lblStrWhere.Text);
            this.BindData();

            //先判断查询条件，设置文件名
            StringBuilder strFileName = new StringBuilder();
            strFileName.Append("厂家列表");
            this.lblFileName.Text = strFileName.ToString();
        }

        /// <summary>
        /// Handles the Click event of the btnSetPageSize control.设置分页页数
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnSetPageSize_Click(object sender, EventArgs e)
        {
            if (this.txtPageSize.Text.Trim() != "")
            {
                if (this.txtPageSize.Text.Trim() != "0")
                {
               //     this.AspNetPager.PageSize = int.Parse(this.txtPageSize.Text.Trim());
                    this.BindData();
                }
                else
                {
              //      this.AspNetPager.PageSize = 10;
                    this.BindData();
                }
            }
            else
            {
              //  this.AspNetPager.PageSize = 10;
                this.BindData();
            }
        }

        /// <summary>
        /// Handles the Click event of the btnExportExcel control.导出到Excel
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
            
                this.lblFileName.Text = "厂家列表";
            
           // UART.BLL.Sales.Manufacturer bll = new UART.BLL.Sales.Manufacturer();
          var ds = mk.l.Sales_Manufacturer.ToList();

            this.myGridView.DataSource = ds;
            this.myGridView.DataBind();
            //把GridView的第一列、编辑删除列设置为不显示
            this.myGridView.Columns[0].Visible = false;
            this.myGridView.Columns[1].Visible = false;
            this.myGridView.Columns[8].Visible = false;
            this.myGridView.Columns[9].Visible = false;
            this.myGridView.Columns[10].Visible = false;

            this.DataToExcel(this.lblFileName.Text, myGridView);
        }


        /// <summary>
        /// 如果没有重写以下方法，在GridView导出Excel时会报错，类型GridView的控件myGridView必须放在具有runat=server的窗体标记内
        /// </summary>
        /// <param name="control"></param>
        public override void VerifyRenderingInServerForm(Control control)
        {
            //base.VerifyRenderingInServerForm(control);
        }

        /// <summary>
        ///  把GirdView导出成Excel
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="myGridView">My grid view.</param>
        private void DataToExcel(string fileName, GridView myGridView)
        {
            //定义文档类型、字符编码
            Response.Clear();
            Response.Buffer = false;
            //Response.Charset = "utf-8";
            Response.Charset = "GB2312";
            //下面这行很重要， attachment 参数表示作为附件下载，您可以改成 online在线打开
            //filename=FileFlow.xls 指定输出文件的名称，注意其扩展名和指定文件类型相符，可以为：.doc || .xls || .txt ||.htm
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ".xls");
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
            //Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            //Response.ContentType指定文件类型 可以为application/ms-excel || application/ms-word || application/ms-txt || application/ms-html || 或其他浏览器可直接支持文档
            Response.ContentType = "application/ms-excel";
            this.EnableViewState = false;
            //System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
            //定义一个输入流
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
            //将目标数据绑定到输入流输出
            myGridView.RenderControl(oHtmlTextWriter);
            Response.Write(oStringWriter.ToString());
            Response.End();
        }


    }
}
